package com.linker.progress;

import java.io.FileWriter;
import java.math.BigInteger;
import com.linker.desktop.MainWindow;

public class CIAKernel extends Thread
{
	private int k;
	private BigInteger n;
	private BigInteger union_index;
	private BigInteger[] arr_big;
	
	public void run()
	{
		try
		{
			FileWriter sim_union_filewriter = new FileWriter(Integer.toString(this.k) + "_sim_union.txt");
			FileWriter all_union_filewriter = new FileWriter(Integer.toString(this.k) + "_all_union.txt");
			FileWriter min_value_filewriter = new FileWriter(Integer.toString(this.k) + "_min_value.txt");

			arr_big = new BigInteger[k];
			n = new BigInteger("2");
			n = n.pow(k);
			System.out.println(n.toString());
			
			MainWindow.ui_progressbar.setMaximum(n.intValue());
			MainWindow.ui_progressbar.setMinimum(0);
			union_index = new BigInteger("1");
			for (; union_index.compareTo(n) <= 0; union_index = union_index.add(new BigInteger("2")))
			{
				for (int i = 0; i <= (k - 1); i++)
				{
					BigInteger tmp;
					tmp = union_index.multiply( new BigInteger("2").pow(i) );
					tmp = tmp.remainder(n.subtract(new BigInteger("1")));
					
					if ( tmp.compareTo(new BigInteger("0")) <= 0 )
					{
						tmp = tmp.add(n.subtract(new BigInteger("1")));
						
					}
					arr_big[i] = tmp;
				}
				
				
				// ---- 检测是不是sim_union，并输出
				boolean is_ok = true;
				for (int i = 1; is_ok && i <= (k - 1); i++)
				{
					if (arr_big[i].compareTo(arr_big[0]) <= 0)
					{
						is_ok = false;
					}
				}
				if (is_ok)
				{
					for (int i = 0; i <= (k - 1); i++)
					{
						sim_union_filewriter.write(arr_big[i].toString() + " ");
					}
					sim_union_filewriter.write("\r\n");
				}
				
				
				// ---- 检测是不是all_union，并输出
				boolean is_all_union = true;
				for (int i = 1; is_all_union && i <= (k - 1); i++)
				{
					if (arr_big[i].compareTo(arr_big[0]) < 0)
					{
						is_all_union = false;
					}
				}
				if (is_all_union)
				{
					for (int i = 0; i <= (k-1); i++)
					{
						all_union_filewriter.write(arr_big[i].toString() + " ");
					}
					all_union_filewriter.write("\r\n");
					min_value_filewriter.write(arr_big[0].toString() + "\r\n");
				}
				
				CIASignal.current_union_index = union_index;
				MainWindow.ui_progressbar.setValue(union_index.intValue());
				MainWindow.ui_progress_msg.setText(union_index.toString() + "/" + n.toString());
				
			}
			sim_union_filewriter.close();
			all_union_filewriter.close();
			min_value_filewriter.close();
			MainWindow.ui_progress_msg.setText("Done.");

		} catch (Exception e)
		{
			// TODO: handle exception
		}
	}

	public CIAKernel(String k_str)
	{
		this.k = Integer.valueOf(k_str);
	}

}
